package com.timepies.database;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

//http://www.html.it/pag/49180/database-e-sqlite/
public class DbManager extends DbHelper {

	private static DbManager dbManager;

	public DbManager(Context context) {
		super(context);
	}

	public static DbManager getDB(Context c) {
		if (dbManager == null)
			dbManager = new DbManager(c);

		return dbManager;
	}

	public static DbManager getDB(Activity a) {

		return getDB(a.getApplicationContext());
	}

	public void save(String sub, String txt, String date) {
		SQLiteDatabase db = super.getWritableDatabase();

		ContentValues cv = new ContentValues();
		cv.put(DbConstant.FIELD_SUBJECT, sub);
		cv.put(DbConstant.FIELD_TEXT, txt);
		cv.put(DbConstant.FIELD_DATE, date);
		try {
			db.insert(DbConstant.TBL_NAME, null, cv);
		} catch (SQLiteException sqle) {
			// Gestione delle eccezioni
		}
	}

	public void update(String sub, String txt, String date, long id) {
		SQLiteDatabase db = super.getWritableDatabase();

		ContentValues cv = new ContentValues();
		cv.put(DbConstant.FIELD_SUBJECT, sub);
		cv.put(DbConstant.FIELD_TEXT, txt);
		cv.put(DbConstant.FIELD_DATE, date);
		try {
			db.update(DbConstant.TBL_NAME, cv, DbConstant.FIELD_ID + "=?",
					new String[] { Long.toString(id) });
		} catch (SQLiteException sqle) {
			// Gestione delle eccezioni
		}
	}

	public boolean delete(long id) {
		SQLiteDatabase db = super.getWritableDatabase();
		try {
			if (db.delete(DbConstant.TBL_NAME, DbConstant.FIELD_ID + "=?",
					new String[] { Long.toString(id) }) > 0)
				return true;
			return false;
		} catch (SQLiteException sqle) {
			return false;
		}

	}

	public Cursor cursor() {
		Cursor crs = null;
		try {
			SQLiteDatabase db = super.getReadableDatabase();
			crs = db.query(DbConstant.TBL_NAME, null, null, null, null, null,
					null, null);
		} catch (SQLiteException sqle) {
			return null;
		}
		return crs;
	}

}